package com.zidongxiangxi.clock.server.message.callback;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zidongxiangxi.clock.server.repository.ClockDao;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * MQ消息回调处理
 *
 * @author chenxudong
 * @date 2020/07/30
 */
@Slf4j
@RequiredArgsConstructor
public class MessageCallBack implements RabbitTemplate.ConfirmCallback {
    private final ClockDao alarmClockManger;
    private final Executor asyncExecutor;

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        log.info("message confirmCallback, correlationData = {}, ack = {}, cause ={}", correlationData, ack, cause);
        if (ack) {
            if (Objects.nonNull(correlationData)) {
                String alarmId = correlationData.getId();
                if (StringUtils.isNotEmpty(alarmId)) {
                    try {
                        CompletableFuture.runAsync(() -> alarmClockManger.removeById(alarmId), asyncExecutor);
                        log.info("success to clock ! id = {}", alarmId);
                    } catch (Exception e) {
                        log.error("fail to delete clock! id = {}", alarmId);
                    }
                }
            }
        } else {
            log.error("fail to send message!, correlationData = {}", JSON.toJSONString(correlationData));
        }
    }

}
